package org.yunfeng.manage.base.core.facade;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yunfeng.manage.base.api.facade.ItemServiceFacade;
import org.yunfeng.manage.base.api.pojo.Item;
import org.yunfeng.manage.base.api.pojo.ItemDesc;
import org.yunfeng.manage.base.core.mapper.ItemDescMapper;
import org.yunfeng.manage.base.core.mapper.ItemMapper;
import org.yunfeng.manage.common.result.EasyUIResult;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Transactional
@Service("itemServiceFacade")
public class ItemServiceFacadeImpl implements ItemServiceFacade {

	@Resource
	private ItemMapper itemMapper;
	@Resource
	private ItemDescMapper itemDescMapper;

	// 分页查询
	@Override
	public EasyUIResult queryItemList(Integer page, Integer rows) {
		// 怎么将数据封装到EasyUIResult
		PageHelper.startPage(page, rows);
		List<Item> itemList = itemMapper.queryItemList();

		// 为线程安全，要把数据封装到PageInfo对象
		PageInfo<Item> pageInfo = new PageInfo<Item>(itemList);
		// EasyUIResult提供多个构造方法，以一个属性写入
		return new EasyUIResult(pageInfo.getTotal(), pageInfo.getList());
	}

	// 新增
	@Override
	public void saveItem(Item item, String desc) {
		item.setStatus(1);
		item.setCreated(new Date());
		item.setUpdated(item.getCreated());
		itemMapper.insertSelective(item);

		// 保存商品描述
		ItemDesc itemDesc = new ItemDesc();
		itemDesc.setItemId(item.getId()); // mybatis插入数据后自动回装id
		itemDesc.setItemDesc(desc);
		itemDesc.setCreated(new Date());
		itemDesc.setUpdated(itemDesc.getCreated());
		itemDescMapper.insertSelective(itemDesc);
	}

	// 修改
	@Override
	public void updateItem(Item item) {
		item.setUpdated(new Date());
		itemMapper.updateByPrimaryKeySelective(item);
	}

	// 删除
	@Override
	public void deleteByIds(String ids) {
		itemDescMapper.deleteByIds(ids);
		itemMapper.deleteByIds(ids);
	}

	// 查找商品描述信息
	@Override
	public ItemDesc queryDescById(Long id) {
		return itemDescMapper.selectByPrimaryKey(id);
	}

	// 上架
	@Override
	public void reshelfItem(long[] ids) {
		for (long id : ids) {
			Item item = new Item();
			item.setId(id);
			item.setStatus(1);
			item.setUpdated(new Date());
			itemMapper.updateByPrimaryKeySelective(item);
		}
	}

	// 下架
	@Override
	public void instockItem(long[] ids) {
		for (long id : ids) {
			Item item = new Item();
			item.setId(id);
			item.setStatus(2);
			item.setUpdated(new Date());
			itemMapper.updateByPrimaryKeySelective(item);
		}
	}
}
